<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/bootstrap-icons.css">
    <link rel="stylesheet" href="/css/flatpickr.css">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- 日期选择器 -->
    <title>信息完善</title>
    <style>
        .auth-card {
            max-width: 700px;
            margin: 2rem auto;
        }
        .avatar-preview {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
        }
        .form-note {
            font-size: 0.875rem;
            color: #6c757d;
            margin-top: 0.5rem;
        }
        .address-group .form-control {
            margin-bottom: 0.5rem;
        }
    </style>
</head>
<body class="bg-light">
<div class="auth-card card">
    <div class="card-header">
        <h2 class="h5 mb-0">用户信息完善</h2>
    </div>
    <div class="card-body">
        <!--/*@thymesVar id="info" type="com.niit.entity.Info"*/-->
        <form th:action="@{/api/account/infoUpdate}" method="post" th:object="${info}" enctype="multipart/form-data">
            <!-- 基础信息 -->
            <div class="row mb-3">
                <!-- 头像上传 -->
                <div class="mb-4">
                    <label class="form-label">头像</label>
                    <div class="flex-grow-1">
                        <div id="errorMsg" class="text-danger mt-1"></div>
                        <img th:src="@{'data:image/jpeg;base64,' + ${session.avatarBase64}}" id="preview" class="mt-2" style="max-width: 200px;">
                        <div class="form-note">支持 JPG/PNG 格式，大小不超过 2MB</div>
                        <input type="file" class="form-control"
                               name="avatar" id="avatarInput"
                               accept="image/jpeg, image/png"
                               onchange="validateAndPreview(this)">
                    </div>
                </div>

                <div class="col-md-6">
                    <label class="form-label">用户名</label>
                    <input type="text" class="form-control" th:field="*{username}" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">真实姓名</label>
                    <input type="text" class="form-control" th:field="*{realName}">
                </div>
                <div class="col-md-6">
                    <label class="form-label">性别</label>
                    <div class="btn-group w-100">
                        <input type="radio" class="btn-check" name="gender" id="male" value="M" th:checked="(*{gender} == 'M')">
                        <label class="btn btn-outline-primary" for="male">男</label>

                        <input type="radio" class="btn-check" name="gender" id="female" value="F" th:checked="(*{gender} == 'F')">
                        <label class="btn btn-outline-primary" for="female">女</label>
                    </div>
                </div>
                <div class="col-md-6">
                    <label class="form-label">邮箱</label>
                    <input type="text" class="form-control" th:field="*{email}">
                </div>
                <div>
                    <label class="form-label" th:if="${session.loginType} == 1">个人描述</label>
                    <label class="form-label" th:if="${session.loginType} == 2">个人/代表企业描述</label>
                    <label class="form-label" th:if="${session.loginType} == 3">个人描述</label>
                    <textarea name="description" class="form-control" th:field="*{description}" rows="5"></textarea>
                </div>
            </div>

            <!-- 证件信息 -->
            <div class="row mb-3">
                <div class="col-md-6">
                    <label class="form-label">身份证号码</label>
                    <input type="text" class="form-control"
                           th:field="*{idCard}"
                           name="idCard"
                           pattern="\d{17}[\dXx]">
                    <div class="form-note">请填写第二代居民身份证号码</div>
                </div>
                <div class="col-md-6">
                    <label class="form-label">出生日期</label>
                    <input type="date" class="form-control"
                           th:field="*{birthday}"
                           name="birthday"
                           id="birthdayPicker">
                </div>
            </div>

            <!-- 联系信息 -->
            <div class="row mb-3">
                <div class="col-md-6">
                    <label class="form-label">手机号码</label>
                    <input type="tel" class="form-control"
                           th:field="*{phone}"
                           name="phone"
                           required
                           pattern="1[3-9]\d{9}">
                </div>
                <div class="col-md-6">
                    <label class="form-label">邮政编码</label>
                    <input type="number" class="form-control"
                           th:field="*{region.code}"
                           name="code"
                           id="codeId"
                           readonly>
                </div>
            </div>

            <!-- 地址选择 -->
            <div class="mb-3 address-group">
                <label class="form-label">地址选择</label>
                <div class="row">
                    <div class="col-4">
                        <select class="form-select" id="provinceSelect" onchange="changeNext(this,$('#citySelect'))">
                            <option value="">选择省份</option>
                        </select>
                    </div>
                    <div class="col-4">
                        <select class="form-select" id="citySelect" onchange="changeNext(this,$('#townSelect'))" disabled>
                            <option value="">选择城市</option>
                        </select>
                    </div>
                    <div class="col-4">
                        <select class="form-select" id="townSelect" onchange="changeNext(this,$('#streetSelect'))" disabled>
                            <option value="">选择区县</option>
                        </select>
                    </div>
                </div>

                <div class="mt-2">
                    <input type="text" class="form-control"
                           placeholder="详细地址（门牌号等）"
                           name="addressDetail"
                           th:field="*{addressDetail}">
                </div>
                <div class="mt-2" th:if="(*{region.code} != null)">
                    <label class="form-label">已选地址</label>
                    <input type="text" class="form-control"
                           th:field="*{region.fullName}"
                           disabled>
                </div>
            </div>
            <div class="row mb-3" th:if="${session.loginType} != 3">
                <div class="col-md-0" th:if="${session.loginType} == 1">
                    <label class="form-label">简历上传(仅支持pdf)</label>
                    <input type="file" class="form-control col-md-5"
                           name="resumeFile" id="resumeInput"
                           accept="application/pdf">
                </div>

                <div class="col-md-0" th:if="${session.loginType} == 2">
                    <label class="form-label">企业选择/认证</label>
                    <input type="text" class="form-control"
                           th:field="${session.account.company.companyName}"
                           name="companyName"
                           id="company"
                           readonly>
                </div>
            </div>


            <!-- 隐藏字段 -->
            <input type="hidden" name="createTime" th:field="*{createTime}">
            <input type="hidden" name="updateTime" th:field="*{updateTime}">

            <!-- 提交按钮 -->
            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-check2-circle me-2"></i>提交信息
                </button>
            </div>
        </form>
    </div>
    <script src="/js/jquery.2.1.3.min.js"></script>
    <script src="/js/flatpickr.js"></script>
    <script>
        // 头像预览功能
        // function previewAvatar(input) {
        //     if (input.files && input.files[0]) {
        //         const reader = new FileReader();
        //         reader.onload = function(e) {
        //             document.getElementById('avatarPreview').src = e.target.result;
        //         }
        //         reader.readAsDataURL(input.files[0]);
        //     }
        // }

        function loadProvince(input) {
            if(input != null){
                $.ajax({
                    url: "/api/region/findRegion", // 建议使用绝对路径
                    type: "POST",
                    contentType: "application/json", // 关键设置
                    data: JSON.stringify({ code: -1 }), // 序列化为 JSON
                    success: function(data) {
                        const $province = $('#provinceSelect');
                        $province.empty().append('<option value="">请选择</option>');
                        data.forEach(region => {
                            $province.append(
                                $('<option></option>')
                                    .val(region.code)
                                    .text(region.name)
                            );
                        });
                    },
                    error: function() {
                        $('#provinceSelect').html('<option value="">数据加载失败</option>');
                        console.error('区域数据加载异常');
                    }
                });
            }
        }

        function changeNext(input, next){
            if(input != null){
                $('#codeId').val(input.value)
                if(next != null){
                    if (!input.value) return
                    $.ajax({
                        url: "/api/region/findRegion", // 建议使用绝对路径
                        type: "POST",
                        contentType: "application/json", // 关键设置
                        data: JSON.stringify({ code: input.value }), // 序列化为 JSON
                        success: function (data){
                            next.empty().append('<option value="">请选择</option>')
                            next.prop('disabled', false)
                            data.forEach(region => {
                                next.append(
                                    $('<option></option>')
                                        .val(region.code)
                                        .text(region.name)
                                )
                            })
                        },
                        error: function() {
                            $('#provinceSelect').html('<option value="">数据加载失败</option>');
                            console.error('区域数据加载异常');
                        }
                    });
                }
            }
        }
        $(document).ready(function (){
            loadProvince($('#provinceSelect'))
        });

        function validateAndPreview(input) {
            const errorMsg = document.getElementById('errorMsg');
            const preview = document.getElementById('preview');
            const file = input.files[0];

            // 清除旧数据和错误提示
            errorMsg.textContent = '';
            preview.style.display = 'none';

            // 1. 验证文件存在性
            if (!file) {
                errorMsg.textContent = '请选择文件';
                input.value = ''; // 清空输入
                return;
            }

            // 2. 验证文件类型
            const allowedTypes = ['image/jpeg', 'image/png'];
            if (!allowedTypes.includes(file.type)) {
                errorMsg.textContent = '仅支持 JPG/PNG 格式';
                input.value = '';
                return;
            }

            // 3. 验证文件大小
            const maxSizeMB = 2;
            if (file.size > maxSizeMB * 1024 * 1024) {
                errorMsg.textContent = `文件大小不能超过 ${maxSizeMB}MB`;
                input.value = '';
                return;
            }

            // 4. 预览图片
            const reader = new FileReader();
            reader.onload = (e) => {
                preview.src = e.target.result;
                preview.style.display = 'block';
            };
            reader.readAsDataURL(file);

        }

        $(function() {
            // 1. 拦截表单提交
            $('form').on('submit', function(e) {
                e.preventDefault();
                submitFormAsync(this);
            });

            // 2. 异步提交函数
            function submitFormAsync(form) {
                const formData = new FormData(form);

                $.ajax({
                    url: form.action,
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if (res.code === 200) {
                            parent.layer.msg('保存成功', {icon:1}, () => {
                                const index = parent.layer.getFrameIndex(window.name);
                                parent.location.reload();
                                parent.layer.close(index);
                            });
                        } else {
                            parent.layer.alert(res.msg, {icon:2});
                        }
                    },
                    error: function() {
                        alert('请求异常，请重试');
                    }
                });
            }
        });
    </script>
</div>

</body>
</html>